package com.shop.autoshop.pay.alipay;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @version: 1.0.1
 * @author: lyt
 * @description: 支付示例-后端接口服务->支付宝支付 -> 支付宝支付
 **/

@Slf4j
@Service
public class AlipayServiceImpl implements AlipayService {

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private AlipayProperty alipayProperty;

    @Resource
    private AliPayConfiguration aliPayConfiguration;
    /**
     * 下单
     *
     * @param alipayCreateBean
     * @return AlipayOrderCreate
     */

    @Override
    public AlipayTradePrecreateResponse orderPreCreate(AlipayCreateBean alipayCreateBean) {
        // 构建参数
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(alipayCreateBean.getOutTradeNo());
        model.setTotalAmount(alipayCreateBean.getTotalAmount());
        model.setSubject(alipayCreateBean.getSubject());
        model.setBody(alipayCreateBean.getStoreId());
//        model.setTimeoutExpress(EXPIRE);//超时时间
        // 构建请求
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(alipayProperty.getNotifyUrl());
        request.setBizModel(model);
        // 发起请求
        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
            log.info("alipay create order :{}", JSON.toJSONString(response));
            if (response.getCode().equals("10000") && response.getMsg().equals("Success")) {
                return response;
            } else {
                log.error("支付宝创建订单失败:" + response.getMsg() + " " + response.getSubMsg());
                return null;
            }
        } catch (Exception e) {
            log.error("支付宝创建订单失败:{}", e.getMessage());
            log.error("支付宝创建订单失败:{}", e.fillInStackTrace());
            if (response != null) {
                log.error("支付宝创建订单失败:" + response.getMsg() + " " + response.getSubMsg());
            } else {
                log.error("支付宝创建订单失败");
            }
            return null;
        }
    }

    @Override
    public AlipayTradeQueryResponse orderQuery(String orderNum) {
        AlipayTradeBean alipayTradeBean = new AlipayTradeBean();
        alipayTradeBean.setOutTradeNo(orderNum);
        return tradeQuery(alipayTradeBean);
    }

    public AlipayTradeQueryResponse tradeQuery(AlipayTradeBean alipayTradeBean) {
        log.info("===========交易订单查询============");
        // 构建请求参数
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        if (StringUtils.isNotBlank(alipayTradeBean.getOutTradeNo())) {
            // 商户订单号
            model.setOutTradeNo(alipayTradeBean.getOutTradeNo());
        }
        if (StringUtils.isNotBlank(alipayTradeBean.getTradeNo())) {
            // 支付宝订单号
            model.setTradeNo(alipayTradeBean.getTradeNo());
        }
        // 构建请求
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizModel(model);
        // 发起请求
        AlipayTradeQueryResponse response = null;

        try {
            response = alipayClient.execute(request);
            log.info("order:{}",alipayTradeBean.getOutTradeNo());
            log.info("AlipayTradeQueryRequest:{}",JSON.toJSONString(response));
            if (response.isSuccess()) {
                return response;
            }else{
                return null;
            }
        } catch (Exception e) {
            // throw new BizException("000000", "交易订单查询失败");
            log.error("支付宝订单查询异常：{}",e.getMessage());
            return null;
        }
    }


    /**
     * 验签，是否正确
     */
    @Override
    public boolean checkSign(HttpServletRequest request) {
        Map<String, String[]> requestMap = request.getParameterMap();
        Map<String, String> paramsMap = new HashMap<>();
        requestMap.forEach((key, values) -> {
            String strs = "";
            for (String value : values) {
                strs = strs + value;
            }
            log.info( "alipay notify => {}:{}", key, strs);
            paramsMap.put(key, strs);
        });

        if (requestMap.isEmpty()){
            log.error("request 参数为空");
            return false;
        }
        // 调用SDK验证签名
        try {
            return AlipaySignature.rsaCheckV1(paramsMap, alipayProperty.getAlipayPublicKey(), alipayProperty.getCharset(), alipayProperty.getSignType());
        } catch (AlipayApiException e) {
            log.error("*********************验签失败********************");
            log.error("错误信息：{}",e.getMessage());
            return false;
        }

    }
}
